import { DrawInteractor } from "./drawInteractor";
import RectNodeGraph from "../shape/rect";
import { getScale } from "@/graphviewState";
export class RectDrawInteractor extends DrawInteractor {
  startPoint: { x: number; y: number } = { x: 0, y: 0 };
  currentPoint: { x: number; y: number } = { x: 0, y: 0 };
  drawing: boolean = false;
  ctx: CanvasRenderingContext2D | null;
  isFill = true;
  constructor(target: HTMLCanvasElement) {
    super(target);
    this.ctx = this.target.getContext("2d");
  }
  handleMouseDown(e: MouseEvent) {
    this.drawing = true;
    this.startPoint.x = e.offsetX;
    this.startPoint.y = e.offsetY;
  }
  handleMouseUp(e: MouseEvent) {
    this.handleMouseMove(e);
    this.drawing = false;
    this.drawEnd();
  }
  handleMouseMove(e: MouseEvent) {
    if (this.drawing) {
      this.currentPoint.x = e.offsetX;
      this.currentPoint.y = e.offsetY;
      this.reDraw();
    }
  }
  reDraw() {
    if (this.ctx) {
      this.emit("redraw");
      this.draw();
    }
  }
  draw() {
    if (this.ctx) {
      this.ctx.fillStyle = "rgb(64,158,255)";
      const width = Math.abs(this.currentPoint.x - this.startPoint.x);
      const height = Math.abs(this.currentPoint.y - this.startPoint.y);
      if (this.isFill) {
        this.ctx.fillRect(this.startPoint.x, this.startPoint.y, width, height);
      } else {
        this.ctx.strokeRect(
          this.startPoint.x,
          this.startPoint.y,
          width,
          height
        );
      }
    }
  }
  drawEnd() {
    if (
      this.currentPoint.x === this.startPoint.x &&
      this.currentPoint.y === this.startPoint.y
    ) {
      // 只是在原点点击了一下,不会进行绘制
      return;
    }
    const rect = new RectNodeGraph();
    // 去除缩放对鼠标获取点坐标的影响
    const scale = getScale();
    rect.position = {
      x: (this.currentPoint.x + this.startPoint.x) / (2 * scale),
      y: (this.currentPoint.y + this.startPoint.y) / (2 * scale),
    };
    rect.leftTop = {
      x: this.startPoint.x / scale,
      y: this.startPoint.y / scale,
    };
    const width = Math.abs(this.currentPoint.x - this.startPoint.x) / scale;
    const height = Math.abs(this.currentPoint.y - this.startPoint.y) / scale;
    rect.width = width;
    rect.height = height;
    rect.setOriginRect(this.startPoint.x, this.startPoint.y, width, height);
    this.emit("drawend", rect);
  }
}
